package com.bysc.commentservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.bysc.commentservice.client.UserClient;
import com.bysc.commentservice.entity.CommentParent;
import com.bysc.commentservice.entity.CommentSon;
import com.bysc.commentservice.service.GetParentCommentService;
import com.bysc.commonutils.Results;
import com.bysc.commonutils.vo.UserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class GetParentCommentServiceImpl implements GetParentCommentService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserClient userClient;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<CommentParent> getCommentListByPostIdOrderByLike(String id, Integer page, Integer limit) {
        Query query = new Query();
        // 按照最新发布时间降序排序
        Sort sort = Sort.by(Sort.Direction.DESC, "liked");
        // 分页
        query.addCriteria(Criteria.where("isDeleted").is(false));
        Pageable pageable = PageRequest.of(page, limit, sort);
        query.with(pageable);
        List<CommentParent> commentParentList = mongoTemplate.find(query, CommentParent.class);
        for (CommentParent commentParent : commentParentList) {
            String parentUserId = commentParent.getUserId();
            //子评论用户信息
//            UserInfoVo user = JSON.parseObject(JSON.toJSONString(userClient.getUserInfoById(userId).getData().get("user")), UserInfoVo.class);
//            String titles = JSON.toJSONString(user.getTitles());
//            commentSon.setUserAvatar(user.getAvatar());
//            commentSon.setUserUseTitle(titles);
//            commentSon.setUserName(user.getNickname());
            //父评论用户信息
            UserInfoVo parentUser = JSON.parseObject(JSON.toJSONString(userClient.getUserInfoById(parentUserId).getData().get("user")), UserInfoVo.class);
            String nickname = parentUser.getNickname();
            String avatar = parentUser.getAvatar();
            String title = JSON.toJSONString(parentUser.getTitles());
            commentParent.setUserName(nickname);
            commentParent.setUserAvatar(avatar);
            commentParent.setUserUseTitle(title);
        }
        return commentParentList;
    }

}
